package com.xxxx.server.config.security.component;

import com.baomidou.mybatisplus.extension.api.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxxx.server.pojo.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/***
 * 当未登录或者token失效时访问接口时，自定义的返    回结果
 * @author Ding Yi
 */

@Component
public class RestAuthorizationEntryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        System.out.println("request: " + request);
        System.out.println("当未登录或者token失效时访问接口时，自定义的返回结果    ----    RestAuthorizationEntryPoint");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        Result result = Result.error("未登录，请登录！");
        result.setCode(401);

        PrintWriter out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(result));
        System.out.println("RestAuthorizationEntryPoint    ----    doing");

        out.flush();
        out.close();
        System.out.println("RestAuthorizationEntryPoint    ----    end");

    }
}
